package org.jiajie.coffeecodes.demo.jvm.classfile;

import org.jiajie.coffeecodes.demo.jvm.classfile.attributes.AttributeInfo;
import org.jiajie.coffeecodes.demo.jvm.classfile.attributes.impl.CodeAttribute;
import org.jiajie.coffeecodes.demo.jvm.classfile.attributes.impl.ConstantValueAttribute;
import org.jiajie.coffeecodes.demo.jvm.classfile.constantpool.ConstantPool;

/**
 * @author jie
 */
public class MemberInfo {

    private ConstantPool constantPool;
    private int accessFlages;
    private int nameIdx;
    private int descriptorIdx;
    private AttributeInfo[] attributes;

    public MemberInfo(ClassReader reader, ConstantPool constantPool) {
        this.constantPool = constantPool;
        this.accessFlages = reader.readUint16();
        this.nameIdx = reader.readUint16();
        this.descriptorIdx = reader.readUint16();
        this.attributes = AttributeInfo.readAttributes(reader, constantPool);
    }

    static MemberInfo[] readMembers(ClassReader reader, ConstantPool constantPool) {
        int fieldCount = reader.readUint16();
        MemberInfo[] fields = new MemberInfo[fieldCount];
        for (int i = 0; i < fieldCount; i++) {
            fields[i] = new MemberInfo(reader, constantPool);
        }
        return fields;
    }

    public int accessFlages(){
        return this.accessFlages;
    }

    public String name(){
        return this.constantPool.getUTF8(this.nameIdx);
    }

    public String descriptor(){
        return this.constantPool.getUTF8(this.descriptorIdx);
    }

    public CodeAttribute codeAttribute(){
        for (AttributeInfo attrInfo : attributes) {
            if (attrInfo instanceof CodeAttribute) return (CodeAttribute) attrInfo;
        }
        return null;
    }

    public ConstantValueAttribute ConstantValueAttribute(){
        for (AttributeInfo attrInfo : attributes) {
            if (attrInfo instanceof ConstantValueAttribute) return (ConstantValueAttribute) attrInfo;
        }
        return null;
    }
}
